﻿#region Copyright 2011 Mike Goatly
// This source is subject to the the MIT License (MIT)
// All rights reserved.
#endregion

namespace Lifti.Tests.Persistence.LogFileManagerTests
{
    using System.IO;
    using System.Linq;

    using Lifti.Persistence;
    using Lifti.Persistence.IO;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    using Moq;

    /// <summary>
    /// Tests for changing (and indirectly, reading) the state of the log file.
    /// </summary>
    [TestClass]
    public class ChangingLogState
    {
        /// <summary>
        /// The path to the test file.
        /// </summary>
        private const string Path = "testindex.dat";

        /// <summary>
        /// Cleans up before and after each test.
        /// </summary>
        [TestCleanup]
        [TestInitialize]
        public void TestCleanup()
        {
            if (File.Exists(Path))
            {
                File.Delete(Path);
            }

            if (File.Exists(Path + ".txlog"))
            {
                File.Delete(Path + ".txlog");
            }
        }

        /// <summary>
        /// The state of the log file should be written to the log file.
        /// </summary>
        [TestMethod]
        public void ShouldWriteStateToLogFile()
        {
            var dataFile = new Mock<IDataFileManager>(MockBehavior.Strict);
            dataFile.SetupGet(d => d.CurrentLength).Returns(233);

            using (var logFileManager = new LogFileManager(Path))
            {
                logFileManager.InitializeNewLog(dataFile.Object);
                logFileManager.LogState = TransactionLogState.None;
            }

            var expectedData = Data.LogFileHeader(TransactionLogState.None, 233);

            var actual = File.ReadAllBytes(Path);

            Assert.IsTrue(expectedData.SequenceEqual(actual));
        }

        /// <summary>
        /// When the state is changed, the new value should be returned by the property.
        /// </summary>
        [TestMethod]
        public void ChangedStatusShouldBeReturnedByTheProperty()
        {
            var dataFile = new Mock<IDataFileManager>(MockBehavior.Strict);
            dataFile.SetupGet(d => d.CurrentLength).Returns(233);

            using (var logFileManager = new LogFileManager(Path))
            {
                logFileManager.InitializeNewLog(dataFile.Object);
                logFileManager.LogState = TransactionLogState.None;

                Assert.AreEqual(TransactionLogState.None, logFileManager.LogState);
            }
        }
    }
}
